const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-session')
const user = require('./routes/user')
const loan = require('./routes/loan')
const permission = require('./routes/permission')
const approve = require('./routes/approve')
const contract = require('./routes/contract')

const { /*responseHandler,*/checkLogin } = require('./middlewares')

//退出后的token
app.context.blackTokenList = []

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// 处理session
const store = {
  storage: {},
  set(key, session) {
    //生成session内置的key
    this.storage[key] = session
    //也可以存储到数据库
  },
  get(key) {
    //也可以从数据库中获取
    return this.storage[key]
  },
  destroy(key) {
    delete this.storage[key]
    //也可以从数据库中删除该session释放空间
  }
}
app.use(session({store},app))


//响应处理
app.context.success = function (data) {
  this.body = {
    code: 20000, //成功
    data
    // msg 
  }
}
app.context.faild = function (data) {
  this.body = {
    code: 102, //失败
    data
    // msg
  }
}
app.context.tokenExpires = function (data) {
  this.body = {
    code: 603, //权限有问题，需要重定向
    data
    // msg
  }
}
// app.use(responseHandler)
//登录验证
app.use(checkLogin)
// routes
app.use(user.routes(), user.allowedMethods())
app.use(loan.routes(), loan.allowedMethods())
app.use(permission.routes(), permission.allowedMethods())
app.use(approve.routes(), approve.allowedMethods())
app.use(contract.routes(), contract.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
